package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.constant.NumConstant;
import com.hmdp.constant.RedisConstant;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        // 设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        // 写入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryPassThrough(
            ID id, String keyPrefix, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);

        }
        if (json != null) {
            return null;
        }
        R r = dbFallback.apply(id);
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key, "", NumConstant.SHOP_ID_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        String rr = JSONUtil.toJsonStr(r);

        stringRedisTemplate.opsForValue().set(key, rr, time, unit);
        return r;
    }


    public <R, ID> R queryWithLogicalExpire(
            ID id, String keyPrefix, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();

        //1.從店鋪查詢店鋪緩存
        String json = opsForValue.get(key);

        //2.判斷是否存在
        if (StrUtil.isBlankIfStr(json)) {
            //3.未命中,返回null
            return null;
        }
        //4.命中
        //4.1.判斷是否已經過期
        com.hmdp.entity.RedisData redisData = JSONUtil.toBean(json, com.hmdp.entity.RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //4.2.未過期,返回店鋪信息
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }

        //4.3.已過期,嘗試獲取互斥鎖
        String lockKey = RedisConstant.SHOP_ID_LOCK + id;
        boolean isLock = tryLock(lockKey);

        //4.3.1.獲取失敗,返回店鋪信息
        if (!isLock) {
            return r;
        }

        //4.3.2.獲取成功,開啓獨立綫程,返回店鋪信息
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                // 4.3.3查詢數據庫,將店鋪數據寫入redis,並設置邏輯過期時間
                R newR = dbFallback.apply(id);

                this.setWithLogicalExpire(key, newR, time, unit);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 4.3.4釋放互斥鎖
                unlock(lockKey);
            }
        });
        return r;
    }


    public <R,ID> R queryWithMutex(ID id,String keyPrefix,Class<R> type,Function<ID,R> dbFallback,Long time,TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        R r = null;

        if (StrUtil.isNotBlank(json)) {
           r = JSONUtil.toBean(json, type);
            return r;
        }


        if (json != null) {
            return null;
        }

        String lockKey = RedisConstant.SHOP_ID_LOCK + id;

        boolean isLock = tryLock(lockKey);


        try {
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id, keyPrefix, type, dbFallback, time, unit);
            }

           r = dbFallback.apply(id);
            if (r == null) {
                stringRedisTemplate.opsForValue().set(key, "", NumConstant.SHOP_ID_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), time, unit);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }
        return r;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

}
